package com.think.excel;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * @author veione
 * @version 1.0
 * @date 2025/3/5
 */
public class ExcelReader {

    public static Map<String, Object> parseToMap(InputStream fis) throws Exception {
        Map<String, Object> configMap = new HashMap<>();
        Workbook workbook = WorkbookFactory.create(fis);

        Sheet sheet = workbook.getSheetAt(0);
        for (Row row : sheet) {
            Cell keyCell = row.getCell(0);
            Cell valueCell = row.getCell(1);
            if (keyCell != null && valueCell != null) {
                String key = keyCell.getStringCellValue();
                switch (valueCell.getCellType()) {
                    case STRING:
                        configMap.put(key, valueCell.getStringCellValue());
                        break;
                    case NUMERIC:
                        configMap.put(key, valueCell.getNumericCellValue());
                        break;
                    case BOOLEAN:
                        configMap.put(key, valueCell.getBooleanCellValue());
                        break;
                    case FORMULA:
                        configMap.put(key, valueCell.getCellFormula());
                }
            }
        }
        workbook.close();
        return configMap;
    }

    public static void main(String[] args) {
        try {
            InputStream fis = ExcelReader.class.getResourceAsStream("config.xlsx");
            Map<String, Object> configMap = parseToMap(fis);

            ExcelPropertySource propertySource = new ExcelPropertySource("config", configMap);
            System.out.println(propertySource);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
